package site.shader85.Kingdoms.inventory.gui;

import java.util.ArrayList;
import java.util.List;

import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.ItemStack;

import com.google.common.collect.Lists;

import net.md_5.bungee.api.ChatColor;
import site.shader85.Kingdoms.Utils;
import site.shader85.Kingdoms.domain.Domain;
import site.shader85.Kingdoms.inventory.AbstractGUI;
import site.shader85.Kingdoms.kingdom.Kingdom;

public class CompassSelectorGUI extends AbstractGUI {

	private int page = 1;
	private int size = 1;
	private List<Domain> domains;

	public CompassSelectorGUI() {
		super(54, ChatColor.DARK_PURPLE + "&l定位城池", false);
		domains = Lists.newArrayList();
		domains.addAll(Domain.getDomains());
		int size = Domain.getSize();
		this.size = size / 45 + 1;
		refresh();
	}

	@Override
	protected ItemStack index(int slot) {
		if (slot < 54) {
			int id = (page - 1) * 54 + slot;
			if (id + 1 <= domains.size()) {
				Domain d = domains.get(id);
				String owner = d.getOwner();
				ArrayList<String> list = Lists.newArrayList();
				list.add("&r&o所属世界:" + d.getWorldName());
				if (owner == null)
					list.add(ChatColor.RESET + "" + ChatColor.GRAY + "该领地尚未出现领主");
				else {
					list.add(ChatColor.RESET + "" + ChatColor.GRAY + "拥有者:" + owner);
					Kingdom k = Kingdom.getFromOwner(owner);
					list.add(ChatColor.RESET + "" + ChatColor.GRAY + "所属国:" + k.getName());
				}
				list.add(ChatColor.RESET + "" + ChatColor.GRAY + "占地面积:" + d.getXZ() + "m²");
				list.add(ChatColor.RESET + "" + ChatColor.GRAY + "高度:" + d.getHeight() + "m");
				if (owner == null)
					return createSkull("&e&l" + d.getName(), "empty", list);
				else
					return createSkull("&e&l" + d.getName(), owner, list);
			}
		}
		if (slot == 45)
			return create(Material.GOLD_INGOT, "&e上一页", null, false);
		if (slot == 49)
			return create(Material.PAPER, "&e第" + page + "页,共" + size + "页", null, false);
		if (slot == 53)
			return create(Material.GOLD_INGOT, "&e下一页", null, false);
		return null;
	}

	@Override
	public boolean onClick(int slot, ClickType type, HumanEntity player) {
		if (slot < 54 && slot >= 0) {
			int id = (page - 1) * 54 + slot;
			if (id + 1 <= domains.size()) {
				Domain d = domains.get(id);
				World w = player.getWorld();
				if (d.getWorldName().equals(w.getName()) && player instanceof Player)
					((Player) player).setCompassTarget(d.getCore().toLocation(w));
				else
					player.sendMessage(Utils.toMessage("&e[领地]&2你与所选领地不在同一世界,定位失败"));
			}
		}
		if (slot == 45 && page != 1) {
			page -= 1;
			refresh();
		}

		if (slot == 53 && page < size) {
			page += 1;
			refresh();
		}
		return true;
	}

}
